package com.dayuanit.dy15.ebook.bookshop.redis;

import com.dayuanit.dy15.ebook.bookshop.dto.CommodityHomeDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Tuple;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class RedisServiceImpl implements RedisService {

    @Autowired
    private Jedis jedis;

    @Override
    public void zadd(String key, int score, String member) {
        jedis.zadd(key, score, member);
    }

    @Override
    public void zincrby(String key, int number, String member) {
        jedis.zincrby(key, number, member);
    }

    @Override
    public void zrange(String key, int start, int stop) {
        jedis.zrange(key, start, stop);
    }

    @Override
    public List<CommodityHomeDTO> zrevRange(String key, int start, int stop) {
        Set<Tuple> tuples = jedis.zrevrangeWithScores(key, start, stop);

        List<CommodityHomeDTO> collect = tuples.stream().map(tuple -> {

            CommodityHomeDTO commodityHomeDTO = new CommodityHomeDTO();
            commodityHomeDTO.setScore(tuple.getScore());
            commodityHomeDTO.setCommoId(Long.parseLong(tuple.getElement()));
            return commodityHomeDTO;
        }).collect(Collectors.toList());

        return collect;
    }
}
